﻿using System.Collections.Specialized;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace IV.Components.Log
{
    /// <summary>
    /// LogView.xaml 的交互逻辑
    /// </summary>
    public partial class LogComponentView : UserControl
    {
        public LogComponentView()
        {
            InitializeComponent();

            ((INotifyCollectionChanged)LogListView.Items).CollectionChanged += (s, e) => SetItemsControlScrollTrack(LogListView);
        }

        private void SetItemsControlScrollTrack(ItemsControl control)
        {
            var listViewScrollviewer = control.Parent as ScrollViewer;
            if (listViewScrollviewer != null)
            {
                if (listViewScrollviewer.VerticalOffset == listViewScrollviewer.ScrollableHeight)
                {
                    listViewScrollviewer.ScrollToBottom();
                }
            }
        }

        private void PreviewMouseWheel(object sender, MouseWheelEventArgs e)
        {
            if (!e.Handled)
            {
                e.Handled = true;

                // 激发一个鼠标滚轮事件，冒泡给外层接收到
                var eventArg = new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta);
                eventArg.RoutedEvent = MouseWheelEvent;
                eventArg.Source = sender;
                var parent = ((Control)sender).Parent as UIElement;
                parent?.RaiseEvent(eventArg);
            }
        }
    }
}
